﻿using System;
using System.ComponentModel;
using CodeCounsel.SharePoint.RibbonDesigner.Model;
using System.Collections.Specialized;
using System.Windows;
using System.Threading;
using System.Diagnostics;

namespace CodeCounsel.SharePoint.RibbonDesigner.ViewModel
{
    public abstract class BaseViewModel
        : INotifyPropertyChanged
    {
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            VerifyPropertyName(e.PropertyName);
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected void RunUI(Action method)
        {
            if (Thread.CurrentThread != Application.Current.Dispatcher.Thread)
            {
                Application.Current.Dispatcher.Invoke(method, null);
            }
            else
            {
                method();
            }
        }

        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        void VerifyPropertyName(string propertyName)
        {
            // Verify that the property name matches a real,  
            // public, instance property on this object.
            if (TypeDescriptor.GetProperties(this)[propertyName] == null)
            {
                string msg = "Invalid property name: " + propertyName;

                Debug.Fail(msg);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
